package UI;

import groovy.swing.SwingBuilder;
import java.awt.BorderLayout;
import javax.swing.BorderFactory;
import javax.swing.JOptionPane;
import javax.swing.JSplitPane;
import javax.swing.JTree;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeSelectionModel;
import feed.*

//TODO: put commons-client and commons-codec here
//@Grab(group='org.ccil.cowan.tagsoup', module='tagsoup', version='0.9.7')


class Feed { def name; def link; def id; def unread; String toString() { 
    return (unread == "0" ? name : "${name} (${unread})");
  } 
}
//class Item { def title; def contents; String toString() { return title; } }

def feedSvc = new feed.FeedService()

treeTop = new DefaultMutableTreeNode("My Feeds");

for (item in feedSvc.getFeedLocationList())
{
    feed = new Feed(name: item.name, link: item.link)
    treeTop.add(new DefaultMutableTreeNode(feed));
}

// Build the base user interface objects and configure them
swing = new SwingBuilder();
feedTree = new JTree(treeTop);
itemList = swing.list();
itemText = swing.textPane(contentType:'text/html', editable:false);
model = feedTree.getSelectionModel();
model.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
itemList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

// Set up the action closures that will react to user selections
listItems = { feed ->
  rssFile = feedSvc.fileForLink(feed.link);  
  if (rssFile != null) {
    try {
      //println "parsing file ${rssFile}";
      //println (new File(rssFile)).dump();
      rss = new XmlParser().parse(new File(rssFile));
      items = new Vector();
      rss.channel.item.each() {
	item = new Item(title:it.title[0].text(), 
			contents:it.description[0].text());
	items.add(item);
      }
      itemList.setListData(items);
      feed.unread = "0";  // update the unread item count in the feed list
    } catch (Exception e) {
      println "Error during <${feed.name}> RSS parse: ${e}";
    }
  }
}

feedTree.valueChanged = { event ->
  itemText.setText("");  // clear any old item text
  node = (DefaultMutableTreeNode) feedTree.getLastSelectedPathComponent();
  if (node != null) {
    feed = node.getUserObject();
    if (feed instanceof Feed && feed.unread != "0") {
      listItems(feed);
      //def a = new UI.systray.systray()
      def t = new UI.systray.SysTray()
      
    }
  }
}

itemList.valueChanged = { event ->
  item = event.getSource().getSelectedValue();
  if (item != null && item instanceof Item) {
    itemText.setText("<html><body>${item.contents}</body></html>");
  }
}

// Put the user interface together and display it
gui = 
  swing.frame(title:'Programmer\'s RSS reader', location:[100,100], size:[800,600], 
	      defaultCloseOperation:WindowConstants.EXIT_ON_CLOSE) {

    menuBar {
        menu(mnemonic:'F', 'File') {
            menuItem (actionPerformed:this.&print, 'Print')
            separator()
            menuItem (actionPerformed:this.&save, 'Save')
            menuItem (actionPerformed:{System.exit(0)}, 'Quit immediately')
        }
        menu(mnemonic:'O', 'Options') {
            checkBoxMenuItem ('Create Debugging Info', state:true)
        }
        menu(mnemonic:'D', 'Debug') {
            group = buttonGroup()
            radioButtonMenuItem ('Log Level 1', buttonGroup:group, selected:true)
            radioButtonMenuItem ('Log Level 2', buttonGroup:group)
            radioButtonMenuItem ('Log Level 3', buttonGroup:group)
        }
        menu(mnemonic:'F', 'Format') {
            menu('Font') {
                group = buttonGroup()
                radioButtonMenuItem ('Times Roman', buttonGroup:group, selected:true)
                radioButtonMenuItem ('Courier', buttonGroup:group)
            }
        }
        menu(mnemonic:'E', 'Edit') {
            menuItem (actionPerformed:{}, 'Copy')
            menuItem (actionPerformed:{}, 'Cut')
            menuItem (actionPerformed:{}, 'Paste')
            menuItem (actionPerformed:{}, 'Delete')
            separator()
            menu('Object ...') {
                menuItem (actionPerformed:{}, 'Circle')
                menuItem (actionPerformed:{}, 'Square')
                menuItem (actionPerformed:{}, 'Point')
            }
        }
    }


    panel(layout:new BorderLayout()) {
      splitPane(orientation:JSplitPane.HORIZONTAL_SPLIT, dividerLocation:200) {
        scrollPane() {
	  widget(feedTree);
	}

        splitPane(orientation:JSplitPane.VERTICAL_SPLIT, dividerLocation:150) {
          scrollPane(constraints:BorderLayout.CENTER) {
	    widget(itemList);
	  }

	  scrollPane(constraints:BorderLayout.CENTER) {
	    widget(itemText);
	  }
        }
      }
    }
  }

gui.pack();
gui.show();
